import * as XLSX from "xlsx";
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

const userInfo = JSON.parse(localStorage.getItem("authorized-token"));
/*
    * @description: 导出excel
    * @param {Object} json 服务端发过来的数据
    * @param {String} name 导出Excel文件名字

    * @param {String} titleArr 导出Excel表头

    * @param {String} sheetName 导出sheetName名字
    * @return:
    */
export function exportExcel(json, name, titleArr, sheetName) {
  /* convert state to workbook */
  const data = [];
  const keyArray = [];
  const getLength = function (obj) {
    let count = 0;
    for (const i in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, i)) {
        count++;
      }
    }
    return count;
  };
  for (const key1 in json) {
    if (Object.prototype.hasOwnProperty.call(json, key1)) {
      const element = json[key1];
      const rowDataArray = [];
      for (const key2 in element) {
        if (Object.prototype.hasOwnProperty.call(element, key2)) {
          const element2 = element[key2];
          rowDataArray.push(element2);
          if (keyArray.length < getLength(element)) {
            keyArray.push(key2);
          }
        }
      }
      data.push(rowDataArray);
    }
  }
  // keyArray为英文字段表头
  data.splice(0, 0, keyArray, titleArr);
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  // 此处隐藏英文字段表头
  const wsrows = [{ hidden: true }];
  ws["!rows"] = wsrows; // ws - worksheet
  XLSX.utils.book_append_sheet(wb, ws, sheetName);
  /* generate file and send to client */
  XLSX.writeFile(wb, name + ".xlsx");
}

export const readExcel = (
  file: Blob,
  callback: (arg0: XLSX.WorkBook) => void
) => {
  const reader = new FileReader();
  reader.onload = function (e) {
    const data = e.target.result;
    const workbook = XLSX.read(data, { type: "binary" });
    if (callback) callback(workbook);
  };
  reader.readAsBinaryString(file);
};

/**
 * 导出 PDF 文件
 * @param {*} dom 要导出的 PDF 元素
 * @param {*} outFileName 导出的文件名
 */
export const exportPdf = (dom, outFileName) => {
  const element = document.querySelector(dom); // 这个dom元素是要导出pdf的div容器
  // element.style.height = param.height
  setTimeout(() => {
    html2Canvas(element).then(function (canvas) {
      const contentWidth = canvas.width;
      const contentHeight = canvas.height;

      // 一页pdf显示html页面生成的canvas高度;
      const pageHeight = (contentWidth / 592.28) * 841.89;
      // 未生成pdf的html页面高度
      let leftHeight = contentHeight;
      // 页面偏移
      let position = 0;
      // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      const imgWidth = 595.28;
      const imgHeight = (592.28 / contentWidth) * contentHeight;

      const pageData = canvas.toDataURL("image/jpeg", 1.0);

      const pdf = new JsPDF("", "pt", "a4");

      // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
      // 当内容未超过pdf一页显示的范围，无需分页
      if (leftHeight < pageHeight) {
        pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      pdf.save(outFileName + ".pdf");
    });
    // element.style.height = param.minHeight
  }, 0);
};

/**
 * 把二进制文件保存到本地
 */
export function exportFile(file, name) {
  const url = window.URL.createObjectURL(new Blob([file]));
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", name);
  document.body.appendChild(link);
  link.click();

  document.body.removeChild(link); // 下载完成移除元素
  window.URL.revokeObjectURL(url); // 释放掉blob对象
}

/**
 * 是否游客角色
 */
export function isCustomerRole() {
  return userInfo.role === "customer";
}

/**
 * 是否user角色
 */
export function isUserRole() {
  return userInfo.role === "user";
}

/**
 * 是否仓库方角色
 */
export function isWarehouseRole() {
  return userInfo.role === "warehouse";
}

/**
 * 是否admin角色
 */
export function isAdminRole() {
  const list = ["admin", "super"];
  return list.includes(userInfo.role);
}
